import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_community/utils/eventBus.dart';
import 'package:flutter_community/utils/http.dart';
import 'package:flutter_community/utils/preference.dart';
import 'package:flutter_community/utils/showToast.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
// 1.获取短信验证码倒计时
// 1.1定义倒计时变量
  int _count = 60;
//1.2定义倒计时控制器
  bool _isCounting = false;
  // 1.3 定义定时器
  Timer? _timer;
  //1.3定义倒计时方法
  startCountDown() {
    // a.判断是否在倒计时
    if (_isCounting) {
      return;
    }
    //b.设置开始倒计时
    _isCounting = true;
    //c.开启倒计时
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        //1.1 减1
        if (_count > 0) {
          _count--;
        } else {
          // 1.2结束倒计时
          _isCounting = false;
          //1.3 停止定时器
          _timer?.cancel();
          //1.4 重置倒计时
          _count = 60;
        }
      });
    });
  }

//2.获取输入框内容
// 1.定义控制器
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();

//3.获取验证码
  _getCode() async {
// 1.判断输入框内容是否为空
    final phone = _phoneController.text;
    if (phone.isEmpty) {
      ToastMessage.showFail('请输入手机号');
      return;
    }
//2.使用正则约定手机号格式
//测试的手机号:13244668899
    final regPhone = RegExp(r'^1[3456789]\d{9}$');
    if (!regPhone.hasMatch(phone)) {
      //匹配失败
      ToastMessage.showFail('请输入正确的手机号');
      return;
    }

    //3.发送验证码
    startCountDown();
    //4.调接口获取验证码
    final res = await http.get('/code', params: {'mobile': phone});
    // print(res);
    //延迟获取验证码并自动填充
    Future.delayed(const Duration(seconds: 3), () {
      setState(() {
        _codeController.text = res['data']['code'];
      });
    });
  }

  // 4.登录逻辑
  _login() async {
    // 1.获取输入框的值
    final phone = _phoneController.text;
    final code = _codeController.text;
    //2.对手机号和验证码进行校验
    if (phone.isEmpty || code.isEmpty) {
      return ToastMessage.showFail('请输入手机号或验证码');
    }
    //3.手机号和验证码正则校验
    if (!RegExp(r'^1[3456789]\d{9}$').hasMatch(phone)) {
      return ToastMessage.showFail('请输入正确的手机号');
    }
    if (!RegExp(r'^\d{6}$').hasMatch(code)) {
      return ToastMessage.showFail('请输入正确的验证码');
    }
// 4.发送请求
    final res = await http.post('/login', data: {
      'mobile': phone,
      'code': code,
    });
    // print(res);
    //5.保存token
    if (res['code'] != 10000) return;

    try {
      await TokenManager().saveToken(res['data']['token']);
      ToastMessage.showSuccess('登录成功');

      print('登录后token:${TokenManager().getToken()}');
    } catch (e) {
      print('错误打印$e');
    }

    //6.清除定时器
    // _timer?.cancel();

    //发送刷新指令
    eventBus.fire(UserInfoRefreshEvent());
    //7.返回上一页
    Navigator.pop(context);
  }

  @override
  void initState() {
    super.initState();
    setState(() {
      _phoneController.text = '13211112222';
    });
  }

  // @override
  // void dispose() {
  //   super.dispose();
  //   _phoneController.clear();
  //   _codeController.clear();
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '登录',
          style: TextStyle(fontSize: 20),
        ),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: Container(
        // margin: const EdgeInsets.only(top: 20, bottom: 20),
        padding: const EdgeInsets.all(10),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            //头部
            const Text(
              '登录',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            const Text('加入享+,让生活更轻松'),
            const SizedBox(height: 20),
            //输入框:手机号->验证码
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Expanded(
                  child: TextField(
                    controller: _phoneController,
                    keyboardType: TextInputType.phone,
                    maxLength: 11,
                    decoration: const InputDecoration(
                      labelText: '手机号',
                      hintText: '请输入手机号',
                    ),
                  ),
                ),
                //获取验证码按钮
                ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color.fromRGBO(255, 247, 247, 0),
                      shadowColor: Colors.transparent,
                      foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      // startCountDown();
                      _getCode();
                    },
                    child: _isCounting
                        ? Text(
                            '$_count秒后重新获取',
                            style: const TextStyle(color: Colors.grey),
                          )
                        : const Text(
                            '获取验证码',
                            style: TextStyle(
                                color: Color.fromRGBO(174, 202, 214, 1)),
                          ))
              ],
            ),
            // 验证码
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Expanded(
                  child: TextField(
                    controller: _codeController,
                    keyboardType: TextInputType.number,
                    maxLength: 6,
                    decoration: const InputDecoration(
                      labelText: '验证码',
                      hintText: '请输入验证码',
                    ),
                  ),
                )
              ],
            ),
            const SizedBox(
              height: 5,
            ),
            const Text(
              '未注册手机号经验证后将自动登录',
              style: TextStyle(fontSize: 12, color: Colors.grey),
            ),
            const SizedBox(
              height: 20,
            ),
            SizedBox(
                width: MediaQuery.of(context).size.width,
                child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      _login();
                    },
                    child: const Text(
                      '登录',
                      style: TextStyle(color: Colors.white),
                    )))
          ],
        ),
      ),
    );
  }
}
